package com.ys.fmms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ys.fmms.pojo.Role;
import com.ys.fmms.pojo.RolePermission;
import com.ys.fmms.pojo.UserRole;
import com.ys.fmms.service.RolePermissionService;
import com.ys.fmms.service.RoleService;
import com.ys.fmms.service.UserRoleService;
import com.ys.fmms.util.Result;
import com.ys.fmms.util.TimeUtils;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/fmms/roleController")
@Api(tags = "角色相关处理")
public class RoleController {

    @Resource
    private RoleService roleService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private RolePermissionService rolePermissionService;

    @Operation(summary = "给用户分配角色")
    @PostMapping("/assignRoleByUserId/{userId}")
    public Result assignRoleByUserId(
            @PathVariable(value = "userId") String userId,
            @RequestBody List<String> roleIds) {
        try {
            roleService.assignRoleByUserId(userId, roleIds);
            return Result.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.myFail(null).message("分配角色失败");
        }
    }

    @Operation(summary = "获取所有角色信息列表")
    @GetMapping("/getAllRoleList")
    public Result getAllRoleList() {
        List<Role> list = roleService.list();
        return Result.ok(list);
    }

    @Operation(summary = "获取用户的角色信息id列表")
    @GetMapping("/getUserRoleListById")
    public Result getUserRoleListById(@RequestParam String userId) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<UserRole> userRoleList = null;
        // 注意查询为空不需要抛出异常
        userRoleList = userRoleService.list(wrapper);
        return Result.ok(userRoleList);
    }

    @Operation(summary = "获取角色列表通过page和role信息")
    @GetMapping("/getRoleListByOption/{pageNo}/{pageSize}")
    public Result getRoleListByOption(
            @RequestParam(required = false) String roleName,
            @PathVariable(value = "pageNo") Long pageNo,
            @PathVariable(value = "pageSize") Long pageSize
    ) {
        Page<Role> rolePage = new Page<>(pageNo, pageSize);
        IPage<Role> roleIPage;
        try {
            roleIPage = roleService.getRoleListByPageAndRoleName(rolePage, roleName);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.myFail(null).message("获取角色信息失败");
        }
        return Result.ok(roleIPage);
    }

    @Operation(summary = "添加角色/修改角色")
    @PutMapping("/addOrModifyRole")
    public Result addOrModifyRole(@RequestBody Role role) {
        String roleId = role.getId();
        if (!StringUtils.hasText(roleId)) {
            role.setCreateTime(TimeUtils.currentDate());
        } else {
            role.setModifyTime(TimeUtils.currentDate());
        }
        roleService.saveOrUpdate(role);
        return Result.ok();
    }

    @Operation(summary = "删除角色(单个或多个)")
    @DeleteMapping("/deleteRoleByIds")
    public Result deleteRoleByIds(@RequestBody List<String> roleIds) {
        roleService.removeByIds(roleIds);
        return Result.ok();
    }

    @Operation(summary = "根据角色id获取其当前全部菜单ids")
    @GetMapping("/getAllMenuIdsByRoleId/{roleId}")
    public Result getAllMenuIdsByRoleId(@PathVariable(value = "roleId") String roleId) {
        QueryWrapper<RolePermission> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        List<RolePermission> rolePermissionList;
        List<String> roleMenuIds;
        try {
            rolePermissionList = rolePermissionService.list(wrapper);
            roleMenuIds = rolePermissionList.stream()
                    .map(RolePermission::getPermissionId)
                    .collect(Collectors.toList());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.myFail(null).message("获取角色菜单失败");
        }
        return Result.ok(roleMenuIds);
    }
}
